const multer = require('multer');
const path = require('path'); // 引入path模块处理路径（关键修复1）

const uploadRootDir = path.join(__dirname, '../public/avatar'); 

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        // 用path.join处理路径，兼容Windows和mac（关键修复1）
        cb(null, uploadRootDir); 
    },
    filename: (req, file, cb) => {
        const fileName = Date.now() + '-' + file.originalname;
        cb(null, fileName);
    }
});

// 关键修复2：添加.single('avatar')生成单文件处理中间件
const upload = multer({
    storage: storage,
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (req, file, cb) => {
        const allowTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (allowTypes.includes(file.mimetype)) { // 已修正mimetype拼写
            cb(null, true);
        } else {
            cb(new Error('只支持JPG/PNG/WEBP格式!'), false);
        }
    }
}).single('avatar'); // 必须加这行，指定处理name为'avatar'的文件

module.exports = { upload };